<template>
  <el-dialog :title="formData.id?'编辑用户':'添加用户'" :visible="isShow" @close="closeFn">
    <el-form ref="form" :rules="rules" :model="formData">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" />
      </el-form-item>
      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item v-if="!formData.id" label="密码" prop="password">
        <el-input v-model="formData.password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submit">确定</el-button>
      <el-button @click="closeFn">取消</el-button>
    </template>
  </el-dialog>
</template>
<script>
import { addusers, everyusers, editusers } from '@/api/users'
export default {
  props: {
    isShow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        username: '', // 用户名
        email: '', // 电子邮箱
        password: '' // 密码
      },
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '电子邮箱不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 改变回显
    async gerUsersId(id) {
      const res = await everyusers(id)
      //   console.log('一个', res)
      this.formData = res.data
      console.log(this.formData)
    },
    // 提交事件
    async submit() {
    // 进行表单验证
      this.$refs.form.validate()
      if (this.formData.id) {
        await editusers(this.formData)
      } else {
        //   发起添加请求
        await addusers(this.formData)
      }
      //   刷新列表
      this.$emit('updateEvnt')
      // 关闭弹窗
      this.closeFn()
    },
    // 关闭事件
    closeFn() {
      this.$emit('update:isShow', false)
      this.formData = {
        username: '', // 用户名
        email: '', // 电子邮箱
        password: '' // 密码
      }
      // 表单重置
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style>

</style>
